package com.itheima.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1. 设置请求编码
        request.setCharacterEncoding("UTF-8");

        //2. 获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //3. 判断用户名或密码是否正确
        if ("胡莉琪".equals(username) && "0419".equals(password)) {
            // 登录成功了. 存入Session域中,可以在一次会话多次请求之间共享数据
            request.getSession().setAttribute("username", username);

            //---------记住用户名  start-------------
            //1. 获取是否勾选了"记住用户名"
            String rememberMe = request.getParameter("rememberMe");
            //2. 判断是否为 yes
            if("yes".equals(rememberMe)){
                // 勾选了
                Cookie cookie  = new Cookie("rememberMe",username);
                cookie.setMaxAge(7*24*60*60);
                response.addCookie(cookie);
            }
            //---------记住用户名  end-------------


            // 重定向: 浏览器地址栏发生了改变,可以防止重复登录
            response.sendRedirect(request.getContextPath() + "/index.jsp");
            return;
        }

        // 登录失败
        // 将错误信息存入请求域中
        request.setAttribute("msg", "用户名或密码错误~");
        // 转发到登录页面,显示错误信息
        request.getRequestDispatcher("/login.jsp").forward(request, response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
